package com.ssy.lingxi.platform.template.service.serviceimpl.mobile;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.template.PageTemplateTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.marketing.api.feign.ActivityGoodsControllerFeign;
import com.ssy.lingxi.marketing.api.model.request.ProductTagReq;
import com.ssy.lingxi.marketing.api.model.response.ProductTagResp;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.entity.adorn.AppAdorn;
import com.ssy.lingxi.platform.template.service.entity.adorn.PageTemplate;
import com.ssy.lingxi.platform.template.service.entity.collect.MemberShopCollect;
import com.ssy.lingxi.platform.template.service.entity.door.MemberShop;
import com.ssy.lingxi.platform.template.service.entity.door.QMemberShop;
import com.ssy.lingxi.platform.template.service.model.dto.common.CollectDTO;
import com.ssy.lingxi.platform.template.service.model.dto.common.IdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.common.MemberIdAndRoleIdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.mobile.MemberShopInGoodsListMobileDTO;
import com.ssy.lingxi.platform.template.service.model.dto.mobile.MemberShopMainMobileDTO;
import com.ssy.lingxi.platform.template.service.model.qo.MemberShopMobileQO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MemberShopInGoodsListMobileVO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MemberShopListMobileVO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MemberShopMainMobileVO;
import com.ssy.lingxi.platform.template.service.repository.AppAdornRepository;
import com.ssy.lingxi.platform.template.service.repository.MemberShopCollectRepository;
import com.ssy.lingxi.platform.template.service.repository.MemberShopRepository;
import com.ssy.lingxi.platform.template.service.repository.PageTemplateRepository;
import com.ssy.lingxi.platform.template.service.service.mobile.MemberShopMobileService;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import com.ssy.lingxi.product.api.model.request.MemberRequest;
import com.ssy.lingxi.product.api.model.response.store.StoreResponse;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.PopularShopRequest;
import com.ssy.lingxi.report.api.vo.response.PopularShopVO;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.request.StoreIdListRequest;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @author fhj
 * @version 2.0.0
 * @menu mobile - 会员店铺 - 业务实现层
 * @date 2020/12/11
 */
@Slf4j
@Service
public class MemberShopMobileServiceImpl implements MemberShopMobileService {

    @Resource
    private JPAQueryFactory jpaQueryFactory;
    @Resource
    private MemberShopRepository memberShopRepository;
    @Resource
    private MemberShopCollectRepository memberShopCollectRepository;
    @Resource
    private ReportControllerFeign reportControllerFeign;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private ICommodityFeign commodityFeign;
    @Resource
    private PageTemplateRepository pageTemplateRepository;
    @Resource
    private AppAdornRepository appAdornRepository;
    @Resource
    private ActivityGoodsControllerFeign activityGoodsControllerFeign;

    @Override
    @ApiOperation(value = "会员店铺主页")
    public Wrapper<MemberShopMainMobileVO> memberShopMain(MemberShopMainMobileDTO dto, UserLoginCacheDTO user) {
        //根据店铺ID获取会员店铺
        MemberShop memberShop = memberShopRepository.findById(dto.getStoreId()).orElse(null);
        if (memberShop == null) {
            return Wrapper.fail(ResponseCode.PT_NOT_FOUND_MEMBER_SHOP);
        }

        //拷贝
        MemberShopMainMobileVO memberShopMainMobileVO = new MemberShopMainMobileVO();
        BeanUtils.copyProperties(memberShop, memberShopMainMobileVO);

        //封装正在使用的店铺模板装修内容
        List<PageTemplate> pageTemplateList = pageTemplateRepository.findByTypeAndStatusAndShelfAndShopId(
                PageTemplateTypeEnum.SHOP.getCode(),
                CommonBooleanEnum.YES.getCode(),
                CommonBooleanEnum.YES.getCode(),
                dto.getShopId()
        );
        if (CollectionUtil.isNotEmpty(pageTemplateList)) {
            pageTemplateList = pageTemplateList.stream().filter(a ->
                    CollectionUtil.isNotEmpty(a.getUseShopTemplate()) &&
                            a.getUseShopTemplate().stream().anyMatch(b ->
                                    b.getMemberId().equals(memberShop.getMemberId()) && b.getRoleId().equals(memberShop.getRoleId())
                            )
            ).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(pageTemplateList)) {
                if (pageTemplateList.size() > 1) {
                    log.error("正在使用的店铺模板出现多个【检查原因】");
                }
                PageTemplate pageTemplate = pageTemplateList.get(0);

                AppAdorn appAdorn = appAdornRepository.findByTemplateIdAndMemberIdAndRoleId(
                        pageTemplate.getId(),
                        memberShop.getMemberId(),
                        memberShop.getRoleId()
                );
                memberShopMainMobileVO.setTemplateId(pageTemplate.getId());
                if (appAdorn != null) {
                    memberShopMainMobileVO.setAdornContent(appAdorn.getAdornContent());
                }
            }
        }

        //收藏状态
        if (user != null) {
            memberShopMainMobileVO.setCollectStatus(memberShopCollectRepository.existsByShopIdAndMemberIdAndUserId(memberShop.getId(), user.getMemberId(), user.getUserId()));
        }

        //调用商品服务 -> 根据会员ID和角色ID集合获取店铺的主营分类
        try {
            MemberRequest memberRequest = new MemberRequest();
            memberRequest.setMemberId(memberShopMainMobileVO.getMemberId());
            memberRequest.setMemberRoleId(memberShopMainMobileVO.getRoleId());
            Map<String, StoreResponse> map = commodityFeign.getCommodityAndCategoryByMemberIdAndMemberRoleId(
                    Stream.of(memberRequest).collect(toList())
            );
            if (CollectionUtil.isNotEmpty(map) && map.get(memberShopMainMobileVO.getMemberId() + "-" + memberShopMainMobileVO.getRoleId()) != null) {
                memberShopMainMobileVO.setCustomerCategoryName(map.get(memberShopMainMobileVO.getMemberId() + "-" + memberShopMainMobileVO.getRoleId()).getCustomerCategoryName());
            }
        } catch (Exception e) {
            log.error("调用商品服务出错：{}", e.getMessage());
        }

        return Wrapper.success(memberShopMainMobileVO);
    }

    @Override
    @ApiOperation(value = "店铺门户列表")
    public Wrapper<PageData<MemberShopListMobileVO>> memberShopList(MemberShopMobileQO qo, Long shopId) {
        //查询表实体 - 店铺门户
        QMemberShop memberShop = QMemberShop.memberShop;

        //查询条件构造 - 搜索条件
        BooleanBuilder predicates = new BooleanBuilder();

        //搜索条件 - 平台品类ID。调用搜索服务 -> 通过品类查询会员信息（平台品类关联商品，商品关联会员）。
        if (qo.getCategoryId() != null) {
            Wrapper<List<Long>> wrapper = templateFeign.getMemberIdByCategory(shopId, qo.getCategoryId());
            if (wrapper.getCode() == ResponseCode.SUCCESS.getCode()) {
                if (CollectionUtil.isNotEmpty(wrapper.getData())) {
                    predicates.and(memberShop.memberId.in(wrapper.getData()));
                } else {
                    return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
                }
            } else {
                log.info("请求搜索服务失败:{}", wrapper.getMessage());
            }
        }
        //搜索条件 - 店铺名称。
        if (org.apache.commons.lang.StringUtils.isNotBlank(qo.getMemberName())) {
            predicates.and(memberShop.name.like("%" + qo.getMemberName() + "%"));
        }
        //搜索条件 - 省编码。
        if (org.apache.commons.lang.StringUtils.isNotBlank(qo.getProvinceCode())) {
            predicates.and(
                    memberShop.provincesCodeList.like("%" + qo.getProvinceCode() + "%")
                            .or(memberShop.provincesCodeList.eq("0"))
            );
        }
        //搜索条件 - 市编码。
        if (org.apache.commons.lang.StringUtils.isNotBlank(qo.getCityCode())) {
            predicates.and(
                    memberShop.cityCodeList.like("%" + qo.getCityCode() + "%")
                            .or(memberShop.cityCodeList.eq("0"))
            );
        }

        //查询
        JPAQuery<MemberShop> query = jpaQueryFactory.select(memberShop).from(memberShop).where(predicates);

        //总记录数
        long totalCount = query.fetchCount();

        //排序条件 - 信用积分
        if (qo.getOrderType() != null) {
            if (qo.getOrderType().equals(1)) {
                query.orderBy(memberShop.creditPoint.asc());
            }
            if (qo.getOrderType().equals(2)) {
                query.orderBy(memberShop.creditPoint.desc());
            }
        }

        //列表数据
        List<MemberShop> list = query.orderBy(memberShop.createTime.desc()).offset((long) (qo.getCurrent() - 1) * qo.getPageSize()).limit(qo.getPageSize()).fetch();
        if (CollectionUtil.isEmpty(list)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        //调用搜索服务 -> 根据店铺ID集合获取店铺最新上架的商品
        StoreIdListRequest storeIdListRequest = new StoreIdListRequest();
        storeIdListRequest.setIdList(list.stream().map(MemberShop::getId).collect(Collectors.toList()));
        storeIdListRequest.setCount(3);
        storeIdListRequest.setShopId(shopId);
        //todo 需要添加区域筛选
        Wrapper<Map<Long, List<CommoditySearchResponse>>> wrapper = templateFeign.getCommodityListByPublishTime(storeIdListRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("请求搜索服务失败：{}", wrapper.getMessage());
        }

        //封装每个店铺最新上架商品
        List<MemberShopListMobileVO> memberShopListMobileVOList = list.stream().map(a -> {
            MemberShopListMobileVO vo = new MemberShopListMobileVO();
            BeanUtils.copyProperties(a, vo);

            if (wrapper.getData() != null && CollectionUtil.isNotEmpty(wrapper.getData().get(a.getId()))) {
                vo.setProductList(
                        wrapper.getData().get(a.getId()).stream().map(product -> {
                            MemberShopListMobileVO.ProductVO productVO = new MemberShopListMobileVO.ProductVO();
                            BeanUtils.copyProperties(product, productVO);
                            return productVO;
                        }).collect(toList())
                );
            }

            return vo;
        }).collect(toList());

        return Wrapper.success(new PageData<>(totalCount, memberShopListMobileVOList));
    }

    @Override
    @ApiOperation(value = "人气店铺和最新上架三个商品")
    public Wrapper<List<MemberShopListMobileVO>> popularStore(Long shopId, String provinceCode, String cityCode) {
        //调用报表服务 -> 获取人气店铺ID
        PopularShopRequest popularShopRequest = new PopularShopRequest();
        popularShopRequest.setCount(10);
        Wrapper<List<Long>> popularShopIdListWrapper = reportControllerFeign.getPopularShopIdList(popularShopRequest);
        if (popularShopIdListWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", popularShopIdListWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_REPORT_ERROR);
        }
        if (CollectionUtil.isEmpty(popularShopIdListWrapper.getData())) {
            return Wrapper.success(new ArrayList<>());
        }
        QMemberShop qMemberShop = QMemberShop.memberShop;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qMemberShop.id.in(popularShopIdListWrapper.getData()));
        //搜索条件-省编码
        if (StringUtils.isNotBlank(provinceCode)) {
            builder.and(
                    qMemberShop.provincesCodeList.like("%" + provinceCode + "%").or(qMemberShop.provincesCodeList.eq("0")));
        }
        //搜索条件-市编码
        if (StringUtils.isNotBlank(cityCode)) {
            builder.and(qMemberShop.cityCodeList.like("%" + cityCode + "%").or(qMemberShop.cityCodeList.eq("0")));
        }
        List<MemberShop> list = jpaQueryFactory.select(qMemberShop).from(qMemberShop).where(builder).orderBy(qMemberShop.id.desc()).fetch();
        //调用搜索服务 -> 根据店铺ID集合获取店铺最新上架的商品
        StoreIdListRequest storeIdListRequest = new StoreIdListRequest();
        storeIdListRequest.setIdList(list.stream().map(MemberShop::getId).collect(Collectors.toList()));
        storeIdListRequest.setCount(3);
        storeIdListRequest.setShopId(shopId);
        storeIdListRequest.setProvinceCode(provinceCode);
        storeIdListRequest.setCityCode(cityCode);
        Wrapper<Map<Long, List<CommoditySearchResponse>>> wrapper = templateFeign.getCommodityListBySoldCount(storeIdListRequest);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("请求搜索服务失败：{}", wrapper.getMessage());
        }

        //封装每个店铺最新上架商品
        List<MemberShopListMobileVO> memberShopListMobileVOList = list.stream().map(a -> {
            MemberShopListMobileVO vo = new MemberShopListMobileVO();
            BeanUtils.copyProperties(a, vo);

            if (wrapper.getData() != null && CollectionUtil.isNotEmpty(wrapper.getData().get(a.getId()))) {
                vo.setProductList(
                        wrapper.getData().get(a.getId()).stream().map(product -> {
                            MemberShopListMobileVO.ProductVO productVO = new MemberShopListMobileVO.ProductVO();
                            BeanUtils.copyProperties(product, productVO);
                            return productVO;
                        }).collect(toList())
                );
            }

            return vo;
        }).collect(toList());

        return Wrapper.success(memberShopListMobileVOList);
    }

    @Override
    @ApiOperation(value = "人气店铺信息")
    public Wrapper<List<PopularShopVO>> popularStoreMsg(Long shopId) {
        //调用报表服务 -> 获取人气店铺信息
        PopularShopRequest popularShopRequest = new PopularShopRequest();
        popularShopRequest.setCount(10);
        Wrapper<List<PopularShopVO>> popularShopIdListWrapper = reportControllerFeign.getPopularShopList(popularShopRequest);
        if (popularShopIdListWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求报表服务失败:{}", popularShopIdListWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_REPORT_ERROR);
        }
        if (CollectionUtil.isEmpty(popularShopIdListWrapper.getData())) {
            return Wrapper.success(new ArrayList<>());
        }
        return Wrapper.success(popularShopIdListWrapper.getData());
    }

    @Override
    @ApiOperation(value = "店铺门户包含商品列表")
    public Wrapper<List<MemberShopInGoodsListMobileVO>> memberShopInGoodsList(MemberShopInGoodsListMobileDTO dto) {
        //拿到请求参数[ {店铺ID:1, 商品ID:[1,2,3]}, 店铺ID:2, 商品ID:[4,5,6]}, {...}, {...}  ]
        List<MemberShopInGoodsListMobileDTO.MemberShopInGoods> memberShopInGoodsList = dto.getMemberShopInGoodsList();
        if (CollectionUtil.isEmpty(memberShopInGoodsList)) {
            return Wrapper.success(new ArrayList<>());
        }

        //取出所有店铺ID, 根据店铺ID获取店铺, 再按照店铺ID再集合内的顺序进行排序
        List<Long> memberShopIdList = memberShopInGoodsList.stream().map(MemberShopInGoodsListMobileDTO.MemberShopInGoods::getMemberShopId).collect(toList());
        //赛选数据
        QMemberShop qMemberShop = QMemberShop.memberShop;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qMemberShop.id.in(memberShopIdList));
        //搜索条件 - 省编码。
        if (StringUtils.isNotBlank(dto.getProvinceCode())) {
            builder.and(
                    qMemberShop.provincesCodeList.like("%" + dto.getProvinceCode() + "%")
                            .or(qMemberShop.provincesCodeList.eq("0"))
            );
        }
        //搜索条件 - 市编码。
        if (StringUtils.isNotBlank(dto.getCityCode())) {
            builder.and(
                    qMemberShop.cityCodeList.like("%" + dto.getCityCode() + "%")
                            .or(qMemberShop.cityCodeList.eq("0"))
            );
        }
        List<MemberShop> memberShopList = jpaQueryFactory.select(qMemberShop).from(qMemberShop).where(builder).fetch();
        if (CollectionUtil.isEmpty(memberShopList)) {
            return Wrapper.success(new ArrayList<>());
        }
        memberShopList = memberShopList.stream().sorted(Comparator.comparingInt(a -> memberShopIdList.indexOf(a.getId()))).collect(toList());

        //key为店铺ID, value则是每一个店铺ID对应的商品ID
        Map<Long, List<Long>> map = new HashMap<>();
        memberShopInGoodsList.forEach(a -> {
            if (CollectionUtil.isNotEmpty(a.getGoodsId())) {
                map.put(a.getMemberShopId(), a.getGoodsId());
            }
        });

        //拿到每个店铺对应商品的ID去调用搜索服务 -> 查询商品
        List<CommoditySearchResponse> templateResponseList = new ArrayList<>();
        List<ProductTagResp> productList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(map)) {
            //调用搜索服务 -> 查询商品
            List<Long> goodsIdLists = map.values().stream().flatMap(Collection::stream).collect(toList());
            TemplateCommoditySearchRequest searchRequest = new TemplateCommoditySearchRequest();
            searchRequest.setCurrent(1);
            searchRequest.setPageSize(goodsIdLists.size());
            searchRequest.setShopId(dto.getShopId());
            searchRequest.setIdInList(goodsIdLists);
            searchRequest.setProvinceCode(dto.getProvinceCode());
            searchRequest.setCityCode(dto.getCityCode());
            Wrapper<PageData<CommoditySearchResponse>> wrapper = templateFeign.searchCommodityList(searchRequest);
            if (wrapper.getCode() == ResponseCode.SUCCESS.getCode() && CollectionUtil.isNotEmpty(wrapper.getData().getData())) {
                templateResponseList = wrapper.getData().getData();
            }

            //调用营销服务 -> 获取商品的最大优惠价格
            ProductTagReq req = new ProductTagReq();
            req.setShopId(dto.getShopId());
            req.setProductIds(goodsIdLists);
            Wrapper<List<ProductTagResp>> productListWrapper = activityGoodsControllerFeign.getPreferentialPrice(req);
            if (productListWrapper.getCode() == ResponseCode.SUCCESS.getCode() && CollectionUtil.isNotEmpty(productListWrapper.getData())) {
                productList = productListWrapper.getData();
            }
        }

        //组装
        List<CommoditySearchResponse> finalTemplateResponseList = templateResponseList;
        List<ProductTagResp> finalProductList = productList;
        List<MemberShopInGoodsListMobileVO> list = memberShopList.stream().map(a -> {
            MemberShopInGoodsListMobileVO memberShopInGoodsListMobileVO = new MemberShopInGoodsListMobileVO();
            BeanUtils.copyProperties(a, memberShopInGoodsListMobileVO);

            if (CollectionUtil.isNotEmpty(finalTemplateResponseList) && CollectionUtil.isNotEmpty(map)) {
                List<Long> goodsIdList = map.get(a.getId());
                List<CommoditySearchResponse> goodsList = finalTemplateResponseList.stream().filter(b ->
                        goodsIdList != null && goodsIdList.contains(b.getId())
                ).collect(toList());
                memberShopInGoodsListMobileVO.setGoodsVOList(
                        goodsList.stream().map(b -> {
                            MemberShopInGoodsListMobileVO.GoodsVO goods = new MemberShopInGoodsListMobileVO.GoodsVO();
                            BeanUtils.copyProperties(b, goods);
                            goods.setPrice(BigDecimal.valueOf(b.getMin()));

                            if (CollectionUtil.isNotEmpty(finalProductList)) {
                                BigDecimal price = finalProductList.stream().filter(c -> c.getProductId().equals(b.getId())).map(ProductTagResp::getPreferentialPrice).findFirst().orElse(BigDecimal.valueOf(b.getMin()));
                                goods.setPrice(price);
                            }

                            return goods;
                        }).collect(toList())
                );
            }

            return memberShopInGoodsListMobileVO;
        }).collect(toList());

        return Wrapper.success(list);
    }

    @Override
    @ApiOperation(value = "根据会员ID和角色ID获取店铺")
    public Wrapper<MemberShopMainMobileVO> findByMemberIdAndRoleId(MemberIdAndRoleIdDTO dto, UserLoginCacheDTO user) {
        //根据会员ID和角色ID获取会员店铺
        MemberShop memberShop = memberShopRepository.findByMemberIdAndRoleId(dto.getMemberId(), dto.getRoleId());
        if (memberShop == null) {
            return Wrapper.fail(ResponseCode.PT_NOT_FOUND_MEMBER_SHOP);
        }

        //拷贝
        MemberShopMainMobileVO memberShopMainMobileVO = new MemberShopMainMobileVO();
        BeanUtils.copyProperties(memberShop, memberShopMainMobileVO);

        //收藏状态
        if (user != null) {
            memberShopMainMobileVO.setCollectStatus(memberShopCollectRepository.existsByShopIdAndMemberIdAndUserId(memberShop.getId(), user.getMemberId(), user.getUserId()));
        }

        return Wrapper.success(memberShopMainMobileVO);
    }

    @Override
    @ApiOperation(value = "根据店铺ID获取店铺")
    public Wrapper<MemberShop> findById(IdDTO dto) {
        return Wrapper.success(memberShopRepository.findById(dto.getId()).orElse(null));
    }

    @Override
    @ApiOperation(value = "收藏列表")
    public Wrapper<PageData<MemberShop>> collectList(PageVO dto, UserLoginCacheDTO user) {
        //按收藏时间倒序获取当前用户收藏的店铺ID
        Pageable pageable = PageRequest.of(dto.getCurrent() - 1, dto.getPageSize(), Sort.by("createTime").descending());
        Page<MemberShopCollect> page = memberShopCollectRepository.findAllByMemberIdAndUserId(user.getMemberId(), user.getUserId(), pageable);
        List<MemberShopCollect> memberShopCollectList = page.getContent();
        if (CollectionUtil.isEmpty(memberShopCollectList)) {
            log.info("当前用户没有收藏的店铺");
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<Long> memberShopIdList = memberShopCollectList.stream().map(MemberShopCollect::getShopId).collect(toList());

        //根据收藏的店铺ID获取店铺
        List<MemberShop> memberShopList = memberShopRepository.findAllByIdIn(memberShopIdList);

        //组装收藏时间
        memberShopList = memberShopList.stream().peek(a -> a.setCreateTime(
                memberShopCollectList.stream().filter(b ->
                        b.getShopId().equals(a.getId())
                ).map(MemberShopCollect::getCreateTime).findFirst().orElse(null)
        )).sorted(Comparator.comparingInt(a -> memberShopIdList.indexOf(a.getId()))).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(page.getTotalElements(), memberShopList));
    }

    @Override
    @Transactional
    @ApiOperation(value = "收藏/取消收藏")
    public Wrapper<Void> collect(CollectDTO dto, UserLoginCacheDTO user) {
        if (dto.getStatus()) {
            if (memberShopCollectRepository.existsByShopIdAndMemberIdAndUserId(dto.getId(), user.getMemberId(), user.getUserId())) {
                return Wrapper.fail("不能重复收藏，请刷新页面");
            }
            MemberShopCollect collect = new MemberShopCollect();
            collect.setShopId(dto.getId());
            collect.setMemberId(user.getMemberId());
            collect.setUserId(user.getUserId());
            memberShopCollectRepository.saveAndFlush(collect);
        } else {
            memberShopCollectRepository.deleteByShopIdAndMemberIdAndUserId(dto.getId(), user.getMemberId(), user.getUserId());
        }

        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "新入店铺")
    public Wrapper<PageData<MemberShop>> newAddStore(PageVO dto) {
        //获取7天内新加入的店铺
        long time = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -6)).getTime();
        Pageable pageable = PageRequest.of(dto.getCurrent() - 1, dto.getPageSize(), Sort.by("createTime").descending());
        Page<MemberShop> page = memberShopRepository.findAllByCreateTimeGreaterThanEqual(time, pageable);
        return Wrapper.success(new PageData<>(page.getTotalElements(), page.getContent()));
    }


}
